package com.controller;

import com.dao.IEmpDAO;
import com.util.SessionUtil;
import com.vo.Emp;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class EmpController {

	IEmpDAO empDAO = null;
	SqlSession session = null;

	@RequestMapping("selectAllEmp")
	public String selectAllEmp(Model model) throws Exception {
	SessionUtil sessionUtil = new SessionUtil(); //获取mybatis的Session对象
		session = sessionUtil.getSession();
		if (session != null) {
			empDAO = session.getMapper(IEmpDAO.class);//装载接口类
			List<Emp> emps = empDAO.selectAll(); //调用接口中 定义的数据库操作方法
			model.addAttribute("emps", emps);
			//session.commit();  如果遇到 insert delete update 必须执行commit
		}
		sessionUtil.destory(); //关闭session
		return "showEmps.jsp";
	}


	@RequestMapping("delEmp/{id}")
	public String delEmp(@PathVariable("id") int empno) throws Exception {
		SessionUtil sessionUtil = new SessionUtil(); //获取mybatis的Session对象
		session = sessionUtil.getSession();
		if (session != null) {
			empDAO = session.getMapper(IEmpDAO.class);//装载接口类
			int result = empDAO.delEmp(empno); //调用接口中 定义的数据库操作方法
			session.commit();  //如果遇到 insert delete update 必须执行commit
			if (result == 1) {
				System.out.println("删除成功");
			} else {
				System.out.println("删除失败");
			}
		}
		sessionUtil.destory(); //关闭session
		return  "/selectAllEmp";
	}

	@RequestMapping("findEmp/{id}")
	public String findEmpById(@PathVariable("id") int empno, HttpSession session1){
		SessionUtil sessionUtil = new SessionUtil(); //获取mybatis的Session对象
		session = sessionUtil.getSession();
		if (session != null) {
			empDAO = session.getMapper(IEmpDAO.class);//装载接口类
			Emp emp = empDAO.findEmpById(empno); //调用接口中 定义的数据库操作方法
			session1.setAttribute("emp", emp);
			//session.commit();  如果遇到 insert delete update 必须执行commit
		}
		sessionUtil.destory(); //关闭session
		return "/edit.jsp";
	}


	@RequestMapping("updateEmp")
	public String updateEmp(Emp emp){
		SessionUtil sessionUtil = new SessionUtil(); //获取mybatis的Session对象
		session = sessionUtil.getSession();
		if (session != null) {
			empDAO = session.getMapper(IEmpDAO.class);//装载接口类
			int result = empDAO.updateEmp(emp); //调用接口中 定义的数据库操作方法
			session.commit();  //如果遇到 insert delete update 必须执行commit
			if (result == 1) {
				System.out.println("更新成功");
			} else {
				System.out.println("更新失败");
			}
		}
		sessionUtil.destory(); //关闭session
		return "/selectAllEmp";
	}


	}
